package com.windward.vii.web.controller;

import com.windward.vii.common.Constants;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.dao.entity.Goods;
import com.windward.vii.dao.entity.Order;
import com.windward.vii.service.OrderService;
import com.windward.vii.service.UserTokenService;
import com.windward.vii.service.apple.ApplePayService;
import com.windward.vii.utils.Utils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/v1/")
public class ApplePayController {

    @Resource
    UserTokenService userTokenService;
    @Resource
    OrderService orderService;
    @Resource
    ApplePayService applePayService;

//    @RequestMapping(value = "api1/apple/pay/verify", method = RequestMethod.POST)
//    @ResponseBody
//    public JsonResult verifyApplePayResult(@RequestParam("receipt-data") String receiptData,
//                                           @RequestParam() String orderSn,
//                                           @RequestHeader(value="token") String token) {
//
//        Order order = orderService.selectBySn(orderSn);
//        if(order == null) {
//            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "购买订单不存在");
//        }
//        Long uid = userTokenService.getUidByToken(token);
//        if(!uid.equals(order.getUid())) {
//            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "支付订单与支付用户不匹配");
//        }
//        if(order.getPayStatus() != Constants.Order.ORDER_STATUS_PAY_SUCCESS) {
//            return orderService.paySuccess(order, receiptData);
//        } else {
//            return JsonResult.success("订单已完成支付");
//        }
//    }

    @RequestMapping(value = "api1/apple/pay/verify", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult verifyApplePayResult(@RequestParam("receipt-data") String receiptData,
                                           @RequestParam("orderSn") String goodsSn,
                                           HttpServletRequest request,
                                           @RequestHeader(value="token") String token) {
        Long uid = userTokenService.getUidByToken(token);
        String ip = Utils.getRemoteHost(request);
        return applePayService.verify(uid, goodsSn, receiptData, ip);
    }

}
